<template>
  <div class="game-container">
    <div class="game-header">
      <button 
        v-if="keySettings.showBackButton" 
        class="back-button" 
        @click="goBack" 
        tabindex="0" 
        ref="backButton"
      >
        返回
      </button>
      <h1 class="game-title">脑筋急转弯</h1>
    </div>
    
    <div class="game-content">
      <div class="teaser-card">
        <div class="progress-bar">
          <div class="progress" :style="{ width: `${(currentIndex + 1) / teasers.length * 100}%` }"></div>
          <div class="progress-text">{{ currentIndex + 1 }} / {{ teasers.length }}</div>
        </div>
        
        <div class="question-container">
          <h2 class="question">{{ currentTeaser.question }}</h2>
        </div>
        
        <div class="answer-container" v-if="showAnswer">
          <div class="answer">{{ currentTeaser.answer }}</div>
        </div>
        
        <div class="controls">
          <button 
            class="control-button prev-button" 
            @click="prevTeaser"
            :disabled="currentIndex === 0"
            tabindex="0"
            ref="prevButton"
          >
            上一题
          </button>
          
          <button 
            class="control-button toggle-button" 
            @click="toggleAnswer"
            tabindex="0"
            ref="toggleButton"
          >
            {{ showAnswer ? '隐藏答案' : '显示答案' }}
          </button>
          
          <button 
            class="control-button next-button" 
            @click="nextTeaser"
            :disabled="currentIndex === teasers.length - 1"
            tabindex="0"
            ref="nextButton"
          >
            下一题
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onBeforeUnmount, computed } from 'vue';
import { useRouter } from 'vue-router';
import { getKeySettings, setupGlobalKeyHandlers, type KeySettings } from '../utils/keySettings';

const router = useRouter();
const backButton = ref<HTMLElement | null>(null);
const prevButton = ref<HTMLElement | null>(null);
const toggleButton = ref<HTMLElement | null>(null);
const nextButton = ref<HTMLElement | null>(null);

// 按键设置
const keySettings = reactive<KeySettings>({
  showBackButton: true,
  enableEscapeKey: true,
  enableContextMenu: true,
  enableKeyboardNavigation: true
});

// 脑筋急转弯数据
const teasers = [
  {
    question: "什么东西越洗越脏？",
    answer: "水"
  },
  {
    question: "什么门永远关不上？",
    answer: "问题"
  },
  {
    question: "什么东西有头无脚？",
    answer: "筷子"
  },
  {
    question: "什么东西晚上才会长出脚？",
    answer: "床"
  },
  {
    question: "什么东西越热越爱出来？",
    answer: "汗"
  },
  {
    question: "什么东西不能用手摸？",
    answer: "眼睛"
  },
  {
    question: "什么车子寸步难行？",
    answer: "风车"
  },
  {
    question: "什么鸡没有翅膀？",
    answer: "田鸡（青蛙）"
  },
  {
    question: "什么书读不完？",
    answer: "天书"
  },
  {
    question: "一个小姑娘，生在水中央，身穿粉红衫，坐在绿船上。是什么？",
    answer: "荷花"
  },
  {
    question: "什么东西可以从天上掉下来，但不会摔坏？",
    answer: "雨"
  },
  {
    question: "什么东西比乌鸦更黑？",
    answer: "乌鸦的影子"
  },
  {
    question: "什么东西有针却不能缝衣服？",
    answer: "指南针"
  },
  {
    question: "什么东西穿的衣服最多？",
    answer: "衣架"
  },
  {
    question: "什么东西越吃越饿？",
    answer: "筷子"
  }
];

const currentIndex = ref(0);
const showAnswer = ref(false);

// 当前题目
const currentTeaser = computed(() => {
  return teasers[currentIndex.value];
});

// 上一题
const prevTeaser = () => {
  if (currentIndex.value > 0) {
    currentIndex.value--;
    showAnswer.value = false;
  }
};

// 下一题
const nextTeaser = () => {
  if (currentIndex.value < teasers.length - 1) {
    currentIndex.value++;
    showAnswer.value = false;
  }
};

// 切换显示答案
const toggleAnswer = () => {
  showAnswer.value = !showAnswer.value;
};

// 返回主页
const goBack = () => {
  router.push('/');
};

// 键盘导航处理
const handleKeyDown = (event: KeyboardEvent) => {
  switch (event.key) {
    case 'ArrowUp':
    case 'ArrowDown':
      navigateFocus(event.key === 'ArrowUp' ? 'up' : 'down');
      break;
    case 'ArrowLeft':
    case 'ArrowRight':
      navigateFocus(event.key === 'ArrowLeft' ? 'left' : 'right');
      break;
    case 'Enter':
      if (document.activeElement === backButton.value) {
        goBack();
      } else if (document.activeElement === prevButton.value) {
        prevTeaser();
      } else if (document.activeElement === toggleButton.value) {
        toggleAnswer();
      } else if (document.activeElement === nextButton.value) {
        nextTeaser();
      }
      break;
  }
};

// 焦点导航
const navigateFocus = (direction: 'up' | 'down' | 'left' | 'right') => {
  const activeElement = document.activeElement;
  
  if (direction === 'up') {
    if (activeElement === prevButton.value || 
        activeElement === toggleButton.value || 
        activeElement === nextButton.value) {
      backButton.value?.focus();
    }
  } else if (direction === 'down') {
    if (activeElement === backButton.value) {
      toggleButton.value?.focus();
    }
  } else if (direction === 'left') {
    if (activeElement === toggleButton.value) {
      prevButton.value?.focus();
    } else if (activeElement === nextButton.value) {
      toggleButton.value?.focus();
    }
  } else if (direction === 'right') {
    if (activeElement === prevButton.value) {
      toggleButton.value?.focus();
    } else if (activeElement === toggleButton.value) {
      nextButton.value?.focus();
    }
  }
};

// 加载按键设置的函数
const loadKeySettings = async () => {
  const settings = await getKeySettings();
  Object.assign(keySettings, settings);
};

// 页面获得焦点时重新加载设置
const handleVisibilityChange = () => {
  if (!document.hidden) {
    loadKeySettings();
  }
};

onMounted(async () => {
  // 初始加载按键设置
  await loadKeySettings();
  
  // 设置全局按键处理器
  const cleanup = setupGlobalKeyHandlers(keySettings, {
    onEscape: () => goBack(),
    onKeyDown: keySettings.enableKeyboardNavigation ? handleKeyDown : undefined
  });
  
  // 监听页面可见性变化，当页面重新获得焦点时重新加载设置
  document.addEventListener('visibilitychange', handleVisibilityChange);
  
  // 初始聚焦到返回按钮（如果显示的话）
  if (keySettings.showBackButton) {
    backButton.value?.focus();
  }
  
  // 组件卸载时清理
  onBeforeUnmount(() => {
    cleanup();
    document.removeEventListener('visibilitychange', handleVisibilityChange);
  });
});
</script>

<style scoped>
.game-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  padding: 2rem;
  background-color: #121212;
  color: white;
}

.game-header {
  display: flex;
  align-items: center;
  margin-bottom: 2rem;
  position: relative;
}

.back-button {
  position: absolute;
  left: 0;
  padding: 0.75rem 1.5rem;
  background-color: #333;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 1.2rem;
  transition: background-color 0.3s;
}

.back-button:hover, .back-button:focus {
  background-color: #555;
  outline: 3px solid #4a90e2;
}

.game-title {
  width: 100%;
  text-align: center;
  font-size: 2.5rem;
  margin: 0;
}

.game-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  flex-grow: 1;
}

.teaser-card {
  background-color: #2a2a2a;
  border-radius: 16px;
  padding: 2rem;
  max-width: 800px;
  width: 100%;
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.3);
}

.progress-bar {
  height: 10px;
  background-color: #333;
  border-radius: 5px;
  margin-bottom: 2rem;
  position: relative;
}

.progress {
  height: 100%;
  background-color: #4a90e2;
  border-radius: 5px;
  transition: width 0.3s;
}

.progress-text {
  position: absolute;
  top: -25px;
  right: 0;
  font-size: 1rem;
  color: #aaa;
}

.question-container {
  margin-bottom: 2rem;
  min-height: 150px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.question {
  font-size: 2rem;
  text-align: center;
  line-height: 1.5;
}

.answer-container {
  background-color: #333;
  padding: 2rem;
  border-radius: 8px;
  margin-bottom: 2rem;
  text-align: center;
  min-height: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.answer {
  font-size: 1.8rem;
  color: #4a90e2;
  font-weight: bold;
}

.controls {
  display: flex;
  justify-content: space-between;
  margin-top: 2rem;
}

.control-button {
  padding: 1rem 2rem;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 1.2rem;
  transition: all 0.3s;
}

.control-button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.prev-button, .next-button {
  background-color: #555;
  color: white;
}

.prev-button:hover:not(:disabled), 
.prev-button:focus:not(:disabled), 
.next-button:hover:not(:disabled), 
.next-button:focus:not(:disabled) {
  background-color: #666;
  outline: 3px solid #4a90e2;
}

.toggle-button {
  background-color: #4a90e2;
  color: white;
}

.toggle-button:hover, .toggle-button:focus {
  background-color: #3a80d2;
  outline: 3px solid #4a90e2;
}

/* 适配电视屏幕 */
@media (min-width: 1920px) {
  .game-title {
    font-size: 3rem;
  }
  
  .question {
    font-size: 2.5rem;
  }
  
  .answer {
    font-size: 2.2rem;
  }
  
  .control-button {
    font-size: 1.5rem;
    padding: 1.2rem 2.5rem;
  }
}
</style>